package com.abyss.stream;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
/**
 * @author Abyss
 * @date 2020/10/4
 * @description
 */
public class StreamWordCountDemo {
    public static void main(String[] args) throws Exception {
        // env
        // 注意 流处理的env是StreamExecutionEnvironment
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 设置全局并行度为6
//        env.setParallelism(4);

        // 2. source
        // 通过一个socket, 远程获取源源不断的数据
        DataStreamSource<Long> longDataStreamSource = env.generateSequence(1, 10);
        SingleOutputStreamOperator<String> source = longDataStreamSource.map(new MapFunction<Long, String>() {
            @Override
            public String map(Long value) throws Exception {
                return value.toString();
            }
        });

        // 3. 数据处理
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordWithOne = source.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        }).setParallelism(2);

        // 按照单词进行分组
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = wordWithOne
                .keyBy(0).sum(1);

        // 4. 数据输出
        result.print();


        // 获取执行计划
        System.out.println(env.getExecutionPlan());
        // 流处理 需要显示的提交任务
        env.execute();
    }
}
